package com.example.common.bean;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * 返回结果封装类
 * @param <T>
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@ApiModel
public class ApiResult<T> implements Serializable {
    /**
     * 返回码 0成功，其他失败
     */
    @ApiModelProperty(value = "返回码 0成功，其他失败")
    private int code;

    /**
     * 描述信息
     */
    @ApiModelProperty(value = "描述信息")
    private String message;

    /**
     * 返回结果
     */
    @ApiModelProperty(value = "返回结果")
    private T data;

    public static boolean isSuccess(int code) {
        return ApiCode.SUCCESS.getCode() == code;
    }

    public static ApiResult success() {
        return success(null);
    }

    public static <T> ApiResult<T> success(T data) {
        return new ApiResult(ApiCode.SUCCESS.getCode(), ApiCode.SUCCESS.getMessage(), data);
    }

    public static ApiResult fail() {
        return fail(ApiCode.SYSTEM_FAIL);
    }

    public static <T> ApiResult<T> fail(ApiCode code, Object... messages){
        return failAndGetData(code, null, messages);
    }

    public static <T> ApiResult failAndGetData(ApiCode code, T data, Object... messages) {
        return new ApiResult(code.getCode(), messages == null || messages.length == 0 ? code.getMessage() : String.format(code.getMessage(), messages), data);
    }
}
